import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.senior_homework.entity.Senior
import com.example.senior_homework.utils.localDateToDate
import com.example.senior_homework.viewmodel.MyViewModel
import java.time.LocalDate
import java.time.Year

/*
*author:guyueyuan
*createTime:2024/11/18
*/

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopHead(
    viewModel: MyViewModel,
    currentCheckedDay: LocalDate,
    onDateChanged: (Int, Int) -> Unit,
) {
    var isFormPickerVisible by remember { mutableStateOf(false) }
    var isDatePickerVisible by remember { mutableStateOf(false) }
    var selectedYear by remember { mutableStateOf(LocalDate.now().year) }
    var selectedMonth by remember { mutableStateOf(LocalDate.now().monthValue) }

    TopAppBar(
        colors = TopAppBarColors(
            containerColor = Color(0xff2895F7),
            Color.White,
            Color.White,
            Color.White,
            Color.White,
        ),
        title = {
            Text(
                text = "${selectedYear}年/${selectedMonth}月",
                fontSize =  30.sp,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )
        },
        navigationIcon = {
            IconButton(onClick = { isDatePickerVisible = true }) {
                Icon(Icons.Default.DateRange, contentDescription = "Open year and month picker")
            }
        },
        actions = {
            IconButton(onClick = { isFormPickerVisible=true }) {
                Icon(Icons.Default.Add, contentDescription = "More options")
            }
        },
    )

    if (isDatePickerVisible) {
        YearMonthPicker(
            selectedYear = selectedYear,
            selectedMonth = selectedMonth,
            onDateChanged={month,year->
                selectedYear = year
                selectedMonth = month
                onDateChanged(month,year)
            },
            onDismissRequest = { isDatePickerVisible = false }
        )
    }

    if (isFormPickerVisible) {
        DataCreatePicker(
            viewModel,
            currentCheckedDay =currentCheckedDay,
            onDismissRequest = { isFormPickerVisible = false }
        )
    }


}

@Composable
fun YearMonthPicker(
    selectedYear: Int,
    selectedMonth: Int,
    onDateChanged: (Int,Int) -> Unit,
    onDismissRequest: () -> Unit
) {
    var selectedYearIndex by remember { mutableStateOf(selectedYear - Year.now().minusYears(10).value) }
    var selectedMonthIndex by remember { mutableStateOf(selectedMonth - 1) }

    AlertDialog(
        modifier = Modifier.height(300.dp),
        onDismissRequest = onDismissRequest,
        title = {
            Text("选择年和月", style = MaterialTheme.typography.bodyLarge)
        },
        text = {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                Arrangement.SpaceAround
            ) {
                LazyColumn(
                    state = rememberLazyListState(initialFirstVisibleItemIndex = selectedYearIndex)
                ) {
                    items(Year.now().plusYears(9).value - Year.now().minusYears(10).value + 1) { index ->
                    val year = Year.now().minusYears(10).plusYears(index.toLong()).value
                    Text(
                        color = if(index==selectedYearIndex) Color.Red else Color.Black,
                        text = year.toString(),
                        modifier = Modifier
                            .clickable {
                                selectedYearIndex = index
                            }
                            .padding(vertical = 8.dp),
                    )
                }
                }

                LazyColumn(
                    state = rememberLazyListState(initialFirstVisibleItemIndex = selectedMonthIndex)
                ) {
                    items(12) { index ->
                        val month = index + 1
                        Text(
                            color = if(index==selectedMonthIndex) Color.Red else Color.Black,
                            text = month.toString(),
                            modifier = Modifier
                                .clickable {
                                    selectedMonthIndex = index
                                }
                                .padding(vertical = 8.dp),
                        )
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = {
                onDateChanged(selectedMonthIndex+1,Year.now().minusYears(10).plusYears(selectedYearIndex.toLong()).value)
                onDismissRequest()
            }) {
                Text("确认")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismissRequest) {
                Text("取消")
            }
        }
    )
}

@Composable
fun DataCreatePicker(
    viewModel: MyViewModel,
    onDismissRequest: () -> Unit,
    currentCheckedDay: LocalDate
) {
    var title by remember { mutableStateOf("") }
    var content by remember { mutableStateOf("") }
    var coroutine= rememberCoroutineScope()

    AlertDialog(
        modifier = Modifier.height(600.dp),
        onDismissRequest = onDismissRequest,
        title = { Text("新增日程") },
        text = {
            Column {
                TextField(
                    value = title,
                    onValueChange = { title = it },
                    label = { Text("标题：") },
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(8.dp))
                TextField(
                    value = content,
                    onValueChange = { content = it },
                    label = { Text("内容：") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(500.dp), // 限制高度
                    singleLine = false // 允许多行输入
                )
            }
        },
        confirmButton = {
            TextButton(
                onClick = {
                    // 这里可以处理创建日期的逻辑
                    println("time is $currentCheckedDay")
                    println("Title: $title, Content: $content")

//                    这种机制要会玩，丢给异步，做完后会自动刷新状态，然后相关组件自动重组
                    viewModel.insertSeniorDataAndRefresh(Senior(0,1,title,content, localDateToDate(currentCheckedDay)))
                    onDismissRequest()
                }
            ) {
                Text("确认")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismissRequest) {
                Text("取消")
            }
        }
    )

}


@Preview
@Composable
fun TopHeadPreview() {

}